package db

import (
	"gitee.com/Cookie_XiaoD/go-filestore-server/db/mysql"
	"gitee.com/Cookie_XiaoD/go-filestore-server/db/entities"
)

//UserSignup 用户注册
func UserSignup(userName string,pwd string) (bool,error){
	stmtIn,err:=mysql.DBConn().Prepare("INSERT IGNORE INTO tbl_user(user_name,user_pwd) VALUES(?,?)")
	if err!=nil{
		return false,err
	}
	defer stmtIn.Close()
	r,err:=stmtIn.Exec(userName,pwd)
	if err!=nil{
		return false,err
	}
	if rows,err:=r.RowsAffected();err==nil&&rows>0{
		return true,nil
	}


	return false,err
}

//UserSignIn 用户登录
func UserSignIn(userName string,encPwd string)(bool,error){
	stmtOut,err:=mysql.DBConn().Prepare("SELECT count(1) FROM tbl_user WHERE user_name=? AND user_pwd=? ")
	if err!=nil{
		return false,err
	}
	defer stmtOut.Close()
	row:=stmtOut.QueryRow(userName,encPwd)
	count:=-1
	err=row.Scan(&count)
	if err!=nil{
		return false,err
	}
	if count==1{
		return true,nil
	}
	return false,nil
}

//InsertOrUpdateUserToken 插入或更新用户token
func InsertOrUpdateUserToken(userName string,token string) bool{
	stmt,err:=mysql.DBConn().Prepare("REPLACE INTO tbl_user_token(user_name,user_token) VALUES(?,?)")
	if err!=nil{
		return false
	}
	defer stmt.Close()
	_,err=stmt.Exec(userName,token)
	if err!=nil{
		return false
	}
	return true
}

//CheckUserTokenExists 检查用户Token是否存在
func CheckUserTokenExists(userToken string) bool{
	stmtOut,err:=mysql.DBConn().Prepare("SELECT 1 FROM tbl_user_token WHERE user_token=?")
	if err!=nil{
		return false
	}
	defer stmtOut.Close()
	rows,err:=stmtOut.Query(userToken)
	if err!=nil{
		return false
	}
	defer rows.Close()
	return rows.Next()
}

//GetUserInfo 根据用户名获取用户信息
func GetUserInfo(userName string)(*entities.UserInfo,error){
	stmtOut,err:=mysql.DBConn().Prepare("SELECT user_name,signup_at FROM tbl_user WHERE user_name=?")
	if err!=nil{
		return nil,err
	}
	defer stmtOut.Close()
	userInfo:=&entities.UserInfo{}
	err=stmtOut.QueryRow(userName).Scan(&userInfo.UserName,&userInfo.SignupAt)
	if err!=nil{
		return nil,err
	}
	return userInfo,nil
}